import javax.swing.JOptionPane;

public class GameManager 
{
    public static final int BLACKJACK = 21; //This constant is a global value that is used in the Hand.getScore method. That is why it's public
    private static final int DEALER_LIMIT = 17;
    private CardsDeck deck = new CardsDeck();
    private Hand playerHand = new Hand();
    private Hand computerHand = new Hand();
    
    private boolean playLoopCondition = true;
    
    public void playLoop()
    {
        while(playLoopCondition)
            play();
    }
    
    private void play()
    {
        deck.suffle();
        playerHand.clear();
        computerHand.clear();
        dealTwoCardsTo(playerHand);
        dealTwoCardsTo(computerHand);
        showHandFor("Player",playerHand);
        
        while(playerHand.getScore() < BLACKJACK && JOptionPane.showConfirmDialog(null, "Would you like another card?","",JOptionPane.YES_NO_OPTION)== JOptionPane.YES_OPTION)
        {
                playerHand.addCard(deck.dealCard());        
                showHandFor("Player",playerHand);
        }
        //TODO handle user answer
        if(playerHand.getScore() == BLACKJACK)
           AnnouceBlackJackFor("The player");
        else if(playerHand.getScore() > BLACKJACK)
            AnnounceWinner("The computer");
        else
            computerAutoPlay();
        playLoopCondition = JOptionPane.showConfirmDialog(null, "Would you like to play again?","",JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION;
    }
    
    private void dealTwoCardsTo(Hand hand)
    {
        hand.addCard(deck.dealCard());
        hand.addCard(deck.dealCard());
    }

    private void computerAutoPlay()
    {
        if(computerHand.getScore() == GameManager.BLACKJACK)
        {
            AnnouceBlackJackFor("The computer");
            return;
        }
        while(computerHand.getScore() < DEALER_LIMIT)
            computerHand.addCard(deck.dealCard());
        if(computerHand.getScore() == BLACKJACK)
        {
            AnnouceBlackJackFor("The computer");
            return ;
        }
        
        showHandFor("Computer",computerHand);
        if(computerHand.getScore() > BLACKJACK || computerHand.getScore() < playerHand.getScore())
            AnnounceWinner("The player");
        else
            AnnounceWinner("The computer");
    }
    
    private void showHandFor(String who, Hand hand)
    {
        JOptionPane.showMessageDialog(null,who + " hand is:\n"+ hand + "\n");
    }
    
    private void AnnouceBlackJackFor(String who)
    {
        JOptionPane.showMessageDialog(null, "Black Jack!!! " + who +" is the winner!");
    }
    
    private void AnnounceWinner(String who)
    {
        JOptionPane.showMessageDialog(null, who + " wins!");
    }
}
